
package br.com.menosehmais.framework.util;

import br.com.menosehmais.framework.loggin.StackTraceLogger;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import sun.misc.BASE64Encoder;

/**
 *
 * @author Rafael Quintino Gomes Rosa
 */
public class Hash {
    public enum Algorithm {
        MD5,
        SHA;
    }

    public static String asString(byte[] digest){
        return (new BASE64Encoder()).encode(digest);
    }
    
    public static byte[] generateDigest(Algorithm algorithm, InputStream inputStream) throws IOException{
        byte[] buffer = new byte[1024];

        try {
            MessageDigest md = MessageDigest.getInstance(algorithm.name());

            int bytes = 0;
            while ((bytes = inputStream.read(buffer)) != -1) {
                md.update(buffer, 0, bytes);
            }

            inputStream.reset();

            return md.digest();
            
        } catch(NoSuchAlgorithmException nsae) {
            StackTraceLogger.INSTANCE.printStackTrace(nsae);
        }

        return new byte[0];
    }

    public static byte[] generateDigest(Algorithm algorithm, String string) {
        try {
            MessageDigest md = MessageDigest.getInstance(algorithm.name());

            byte[] buffer = string.getBytes(Charset.forName("UTF-8"));
            int bytes = buffer.length;

            md.update(buffer, 0, bytes);

            return md.digest();

        } catch(NoSuchAlgorithmException nsae) {
            StackTraceLogger.INSTANCE.printStackTrace(nsae);
        }

        return new byte[0];
    }
}
